from django.core.management.base import BaseCommand
from django.utils.text import slugify
from core.models import Document, Tag
from django.db import IntegrityError

class Command(BaseCommand):
    help = '从文档标题重新生成所有标签'

    def generate_unique_slug(self, name):
        """生成唯一的slug"""
        base_slug = slugify(name)
        slug = base_slug
        counter = 1
        while Tag.objects.filter(slug=slug).exists():
            slug = f"{base_slug}-{counter}"
            counter += 1
        return slug

    def handle(self, *args, **options):
        # 清理所有现有标签
        self.stdout.write('清理现有标签...')
        Tag.objects.all().delete()
        
        # 获取所有文档
        documents = Document.objects.filter(is_published=True)  # 只处理已发布的文档
        total = documents.count()
        self.stdout.write(f'开始处理 {total} 个文档...')
        
        # 用于记录标签使用次数
        tag_counts = {}
        
        # 处理每个文档
        for i, doc in enumerate(documents, 1):
            try:
                # 提取标签
                tag_names = doc.extract_tags()
                
                # 创建标签并关联到文档
                for tag_name in tag_names:
                    if tag_name:
                        # 更新标签计数
                        tag_counts[tag_name] = tag_counts.get(tag_name, 0) + 1
                        
                        try:
                            # 获取或创建标签
                            tag = Tag.objects.get(name=tag_name)
                        except Tag.DoesNotExist:
                            # 创建新标签时确保slug唯一
                            slug = self.generate_unique_slug(tag_name)
                            tag = Tag.objects.create(
                                name=tag_name,
                                slug=slug,
                                description=f'包含 {tag_name} 相关的文档'
                            )
                        doc.tags.add(tag)
                
                if i % 10 == 0:
                    self.stdout.write(f'已处理 {i}/{total} 个文档...')
                    
            except Exception as e:
                self.stdout.write(self.style.ERROR(f'处理文档 {doc.title} 时出错: {str(e)}'))
        
        # 输出标签统计信息
        self.stdout.write('\n标签使用统计:')
        for tag_name, count in sorted(tag_counts.items(), key=lambda x: x[1], reverse=True):
            self.stdout.write(f'{tag_name}: {count}次')
        
        self.stdout.write(self.style.SUCCESS('标签重新生成完成！')) 